package com.yklx.youke.service;

import com.yklx.youke.entity.Classroom;
import com.yklx.youke.entity.Session;
import com.yklx.youke.repository.ClassroomRepository;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;

@Service
public class ClassroomService {

    private final ClassroomRepository classroomRepository;

    public ClassroomService(ClassroomRepository classroomRepository) {
        this.classroomRepository = classroomRepository;
    }

    public Classroom getClassroomBySessionId(UUID sessionId) {
        return classroomRepository.findBySessionSessionId(sessionId);
    }

    public Classroom createClassroomForSession(Session session) {
        // Generate a unique room URL
        String roomUrl = generateUniqueRoomUrl();
        String accessCode = generateAccessCode();

        Classroom classroom = new Classroom(session, roomUrl);
        classroom.setAccessCode(accessCode);

        return classroomRepository.save(classroom);
    }

    public Map<String, Object> startStopRecording(UUID sessionId, String action) {
        // This would implement actual recording functionality
        // For now, returning a placeholder response
        if ("start".equals(action)) {
            return Map.of(
                "recordingStatus", "started",
                "recordingUrl", "https://example.com/recordings/" + sessionId.toString()
            );
        } else if ("stop".equals(action)) {
            return Map.of(
                "recordingStatus", "stopped",
                "recordingUrl", "https://example.com/recordings/" + sessionId.toString()
            );
        } else {
            throw new IllegalArgumentException("Invalid action: " + action + ". Use 'start' or 'stop'");
        }
    }

    private String generateUniqueRoomUrl() {
        // Generate a random unique room identifier
        return "room-" + UUID.randomUUID().toString().substring(0, 8);
    }

    private String generateAccessCode() {
        // Generate a random access code
        return String.valueOf((int)(Math.random() * 9000) + 1000); // 4-digit code
    }
}